<template>
	<el-space wrap :fill="true">
		<el-scrollbar :max-height="config.maxHeight">
			<el-card shadow="hover" class="mt10" v-for="(item, index) in formModCollect" :key="item.uniId">
				<AplidForm v-bind="config" :column="column" :key="item.uniId" v-model="item.model" @update:model-value="emitUpdate"></AplidForm>
				<div class="flex space-between align-center mt10">
					<span></span>
					<el-button type="danger" :text="true" v-if="config.delBtn" class="ap-btn" @click="handleRemove(item, index)"> 移除此项 </el-button>
				</div>
			</el-card>
			<div class="flex-center">
				<el-button type="primary" v-if="config.addBtn" class="ap-btn" text @click="handleAdd"> 新增一项 </el-button>
			</div>
		</el-scrollbar>
	</el-space>
</template>

<script setup lang="ts">
import { uniqueId } from 'lodash-es'

const props = defineProps<{
  modelValue:any
  config:any
  column:any
}>()

const emit = defineEmits(['update:modelValue'])

let formModCollect = ref([
	{
		uniId: uniqueId('dynamic'),
		model: {},
	},
])

let refreshReload = false
const emitUpdate = () => {
	const tempArr = formModCollect.value.map((item) => {
		return { ...item.model }
	})
	emit('update:modelValue', tempArr)
}

const handleRemove = (row, index) => {
	formModCollect.value.splice(index, 1)
	emitUpdate()
}
const handleAdd = () => {
	formModCollect.value.push({
		uniId: uniqueId('dynamic'),
		model: {},
	})
}
onUpdated(() => {
  let data :any = []
  try {
     data = JSON.parse(props.modelValue)
  } catch (error) {
    data = props.modelValue || []
  }

  if (!refreshReload || formModCollect.value.length == 0) {
		formModCollect.value = data?.map((item) => {
			return {
				uniId: uniqueId('dynamic'),
				model: {
					...item,
				},
			}
		})||[]
		refreshReload = true
	}
})
</script>

<style scoped></style>
